# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://sf.2dcup.com/dealpay.php'
_QUERY_GATEWAY = 'http://sf.2dcup.com/dealpay_queryorder.php'

APP_CONF = {
    '10151': {  # 金拓支付 快捷 1.5% 10-5000 witch
        'API_KEY': '5c998cad011af3011471f1b30d70abc3'
    },
    '10363': {  # 金拓支付 快捷 1.5% 10-5000 dwc
        'API_KEY': 'b5efd1e4a1cc6ae2630b1a84216b3678'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_charge_sign(parameter, key):
    '''  生成下单签名 '''
    s = '{}{}{}{}{}'.format(
        parameter['appid'], parameter['orderid'], parameter['fee'],
        parameter['tongbu_url'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    _LOGGER.info(u'jintuopay sign str: %s, sign:%s', s, sign)
    return sign


def _get_pay_type(service):
    if service == 'quick':
        pay_type = 23
    else:
        pay_type = 0
    return pay_type


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    parameter_dict = OrderedDict((
        ('appid', app_id),
        ('orderid', pay.id),
        ('fee', int(pay_amount * 100)),
        ('tongbu_url', '{}/pay/api/{}/jintuopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('clientip', user_info.get('device_ip') or '172.200.110.31'),
        ('back_url', '{}/pay/api/{}/jintuopay/{}/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('sfrom', 'wap'),
        ('paytype', _get_pay_type(service)),
    ))
    parameter_dict['sign'] = generate_charge_sign(parameter_dict, api_key)
    _LOGGER.info("jintuopay create charge data: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['orderid'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.get(_GATEWAY, params=parameter_dict, headers=headers, timeout=3)
    resp_obj = json.loads(response.text)
    _LOGGER.info("jintuopay create response.text: %s", response.text)
    if resp_obj['code'] != 'success':
        raise ParamError('jintuopay create error, msg: %s', resp_obj['msg'])
    return {'charge_info': resp_obj['msg']}


def verify_notify_sign(parameter, key):
    '''验证通知签名 '''
    s = '{}{}{}{}{}'.format(
        parameter['orderid'], parameter['result'], parameter['fee'],
        parameter['tradetime'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    calculated_sign = m.hexdigest()
    sign = parameter['sign']
    if sign != calculated_sign:
        _LOGGER.info("jintuopay sign: %s, calculated sign: %", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % parameter)
    return sign


def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    _LOGGER.info("jintuopay notify data: %s, order_id is: %s", data, data['orderid'])
    api_key = _get_api_key(app_id)
    verify_notify_sign(data, api_key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, orderid not exists, data: %s", data)
        raise ParamError('jintuopay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = int(data['result'])
    mch_id = pay.mch_id
    trade_no = data['sforderid']
    total_fee = float(data['fee']) / 100

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 1:
        _LOGGER.info('jintuopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    api_key = _get_api_key(app_id)
    s = '{}{}{}'.format(app_id, pay_order.id, api_key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign_data = m.hexdigest()
    gate_url = '{}?orderid={}&appid={}&sign={}'.format(_QUERY_GATEWAY,
                                                       pay_order.id, app_id, sign_data)
    response = requests.get(gate_url)
    res_obj = json.loads(response.text)
    print res_obj
    result, order_id = int(res_obj['result']), res_obj['orderid']
    if str(order_id) != str(pay_order.id):
        _LOGGER.warn('jintuopay query order, oder id ilegal! {}-{}'.format(
            order_id, pay_order.id))
        return
    if result == 1:
        trade_no = pay_order.third_id
        total_fee = float(pay_order.total_fee)
        extend = {
            'trade_status': result,
            'trade_no': pay_order.third_id,
            'total_fee': total_fee
        }
        _LOGGER.info('jintuopay query order success, mch_id:%s pay_id:%s',
                     pay_order.mch_id, pay_order.id)
        res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                       total_fee, trade_no, extend)
        if res:
            # async notify
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('jintuopay query order fail, status_code: %s', result)
